<template>
  <div style="padding:20px;">
    <el-row :gutter="20">
      <el-col :span="5">
        <div class="container" style="overflow-y: hidden;overflow-x: auto;width:100%;">
          <div style="display: flex;justify-content: center;margin-bottom:20px;">
            <el-button type="primary"
                       @click="firstBtn"
                       size="medium">新增一级组</el-button>
          </div>

          <span style="color:#606266;cursor:pointer"
                @click="() => adminSearch({id:''})">全部</span>&nbsp;
          <el-tree v-if="orgData.showOrgTree"
                   :data="organizationData"
                   node-key="id"
                   default-expand-all
                   :expand-on-click-node="false">
            <span class="custom-tree-node"
                  slot-scope="{node,data}"
                  @mouseenter="mouseenter(data)"
                  @mouseleave="mouseleave">
              <span @click="() => adminSearch(data)">{{ data.org_name }}</span>&nbsp;
              <span v-if="orgData.mouseenterId!=data.id" style="width:100px;display:inline-block !important;">
              </span>
              <span v-if="orgData.mouseenterId==data.id" style="width:100px;display:inline-block !important;">
                <i class="el-icon-plus"
                   @click="() => append(data)"></i>&nbsp;
                <i class="el-icon-edit"
                   @click="() => orgEdit(data)"></i>&nbsp;
                <i class="el-icon-delete"
                   @click="() => orgRemove(data)"></i>&nbsp;
              </span>
            </span>
          </el-tree>
          <!--添加组织名称-->
          <el-dialog :title="orangeTitle"
                     :visible.sync="orgData.editVisible"
                     width="40%">
            <div class="list-group">
              <el-row :gutter="20">
                <el-col :span="4">
                  <div class="list-title"><span class="mast-icon">*</span>组名称:</div>
                </el-col>
                <el-col :span="20">
                  <el-input v-model.trim="orgData.organizationName"
                            placeholder="请输组名称"></el-input>
                </el-col>
              </el-row>
            </div>
            <span slot="footer"
                  class="dialog-footer">
              <el-button size="medium" @click="orgData.editVisible = false">取 消</el-button>
              <el-button size="medium" type="primary" @click="orgSaveEdit">确 定</el-button>
            </span>
          </el-dialog>
        </div>
      </el-col>
      <el-col :span="19">
        <div>
          <div class="container">
            <div class="handle-box">
              <span style="padding:8px;">用户账号/姓名：</span>
              <el-input v-model="searchName"
                        placeholder="用户账号/姓名"
                        class="handle-input mr10"></el-input>
              <span style="padding:8px;">用户类型：</span>
              <el-select v-model="roleId" placeholder="请选择">
                  <el-option
                    v-for="item in roleList"
                    :key="item.id"
                    :label="item.role_name"
                    :value="item.id">
                  </el-option>
                </el-select>
                  <span style="padding:8px;"></span>
              <el-button type="success"
                         size="medium"
                         icon="el-icon-search"
                         @click="handleSearch">搜索</el-button>
              <el-button type="warning"
                         size="medium"
                         icon="el-icon-refresh-left"
                         @click="reset">重置</el-button>
            </div>
            <div class="handle-box">
              <el-button type="primary"
                         icon="el-icon-document-add"
                         size="medium"
                         @click="createBus()">新建</el-button>
              <el-button type="danger"
                         icon="el-icon-delete"
                         size="medium"
                         @click="delAllSelection">批量删除</el-button>
            </div>
            <el-table :data="tableData"
                      border
                      class="table"
                      ref="multipleTable"
                      header-cell-class-name="table-header"
                      @selection-change="handleSelectionChange">
              <el-table-column type="selection"
                               width="50"
                               align="center"
                               fixed="left"></el-table-column>
              <!-- <el-table-column prop="id" label="管理员id" width="80" align="center">
                                <template slot-scope="scope">{{scope.row.id}}</template>
                            </el-table-column> -->
              <el-table-column prop="name"
                               label="账号"
                               align="center">
                <template slot-scope="scope">{{scope.row.account}}</template>
              </el-table-column>
              <el-table-column label="真实姓名"
                               align="center">
                <template slot-scope="scope">{{scope.row.realname}}</template>
              </el-table-column>
              <el-table-column label="手机号"
                               align="center">
                <template slot-scope="scope">{{scope.row.mobile}}</template>
              </el-table-column>
              <el-table-column prop="address"
                               label="邮箱"
                               align="center">
                <template slot-scope="scope">{{scope.row.email}}</template>
              </el-table-column>
              <el-table-column prop="address"
                               label="组织"
                               align="center">
                <template slot-scope="scope">{{scope.row.org_name}}</template>
              </el-table-column>
              <el-table-column prop="address"
                               label="角色"
                               align="center">
                <template slot-scope="scope">
                  <span v-for="(v,i) in scope.row.role"
                        :key="i">{{i==0?v.role_name:','+v.role_name}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="address"
                               label="创建时间"
                               align="center">
                <template slot-scope="scope">{{scope.row.update_time}}</template>
              </el-table-column>
              <el-table-column label="操作"
                               width="220"
                               align="center">
                <template slot-scope="scope">
                  <el-button type="text"
                             icon="el-icon-edit"
                             @click="handleEdit(scope.row)">
                    编辑
                  </el-button>
                  <el-button type="text"
                             icon="el-icon-delete"
                             class="red"
                             style="color:#F56C6C !important;"
                             @click="handleDelete(scope.row)">删除</el-button>
                <el-button type="text"
                             icon="el-icon-tickets"
                             @click="handleLog(scope.row.id)">
                    日志
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination">
              <el-pagination
                layout="sizes,total, prev, pager, next, jumper"
                :current-page="currentPage"
                :page-size="pagesize"
                :page-sizes="[10,20, 50, 100, 150, 200]"
                @size-change="handleSizeChange"
                :total="total"
                @current-change="handleCurrentChange"
              ></el-pagination>
            </div>
          </div>
          <!--添加管理员-->
          <el-dialog :title="adminTitle"
                     :visible.sync="editVisible"
                     width="60%">
            <div class="list-group">
              <el-row :gutter="20">
                <el-col :span="3">
                  <div class="list-title"><span class="mast-icon">*</span>{{modelList.account.name}}:</div>
                </el-col>
                <el-col :span="9">
                  <el-input v-model.trim="modelList.account.value"
                            :placeholder="modelList.account.placeholder"></el-input>
                  <p style="color:red;padding:6px 0;font-size:12px;">账号长度不能小于8位</p>
                </el-col>
                <el-col :span="3">
                  <div class="list-title">{{modelList.password.name}}:</div>
                </el-col>
                <el-col :span="9">
                  <el-input type="password"
                            v-model.trim="modelList.password.value"
                            :placeholder="modelList.password.placeholder"></el-input>
                  <p style="color:red;padding:6px 0;font-size:12px;" v-if="addOrEdit == 1">不填写默认密码：123456,最小长度6位</p>
                  <p style="color:red;padding:6px 0;font-size:12px;" v-else>最小长度6位</p>
                </el-col>
              </el-row>
            </div>
            <div class="list-group">
              <el-row :gutter="20">
                <el-col :span="3">
                  <div class="list-title"><span class="mast-icon">*</span>{{modelList.realname.name}}:</div>
                </el-col>
                <el-col :span="9">
                  <el-input v-model.trim="modelList.realname.value"
                            :placeholder="modelList.realname.placeholder"></el-input>
                </el-col>
                <el-col :span="3">
                  <div class="list-title"><span class="mast-icon">*</span>{{modelList.mobile.name}}:</div>
                </el-col>
                <el-col :span="9">
                  <el-input v-model.trim="modelList.mobile.value"
                            :placeholder="modelList.mobile.placeholder"></el-input>
                </el-col>
              </el-row>
            </div>
            <div class="list-group">
              <el-row :gutter="20">
                <el-col :span="3">
                  <div class="list-title"><span class="mast-icon">*</span>{{modelList.email.name}}:</div>
                </el-col>
                <el-col :span="9">
                  <el-input v-model.trim="modelList.email.value"
                            :placeholder="modelList.email.placeholder"></el-input>
                </el-col>
              </el-row>
            </div>
            <div class="list-group">
              <el-row :gutter="20">
                <el-col :span="4">
                  <div class="list-title"><span class="mast-icon">*</span>{{modelList.org_id.name}}:({{organizationName==''?'未选择':organizationName}})</div>
                </el-col>
                <el-col :span="9">
                  <el-tree v-if="orgData.showOrgTree"
                           :data="organizationData"
                           node-key="id"
                           default-expand-all
                           :expand-on-click-node="false">
                    <span class="custom-tree-node"
                          slot-scope="{node,data}">
                      <span>{{ data.org_name }}</span>
                      <span>
                        <el-button type="text"
                                   size="mini"
                                   @click="() => okClick(data)">选择组</el-button>
                      </span>
                    </span>
                  </el-tree>
                </el-col>
              </el-row>
            </div>
            <div class="list-group">
              <el-row :gutter="20">
                <el-col :span="3">
                  <div>{{modelList.role_ids.name}}:</div>
                </el-col>
                <el-col :span="21">
                  <el-checkbox-group v-model="roleListVal">
                    <el-checkbox :label="val.id"
                                 @change="jsMethod()"
                                 :checked="val.active"
                                 v-for="(val,key) in roleList"
                                 :key="key">{{val.role_name}}</el-checkbox>
                  </el-checkbox-group>
                </el-col>
              </el-row>
            </div>
            <span slot="footer"
                  class="dialog-footer">
              <el-button size="medium" @click="editVisible = false">取 消</el-button>
              <el-button size="medium" type="primary" @click="saveEdit">确 定</el-button>
            </span>
          </el-dialog>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  name: 'admin',
  data () {
    return {
      orgData: {
        editOrAdd: 1,
        editVisible: false,
        organizationName: '',
        organizationId: 0,
        showOrgTree: true,
        mouseenterId: 0,
      },
      adminTitle:'',
      orangeTitle:'',
      roleListVal: [],
      organizationName: '',
      roleList: [],
      searchName: '',
      searchOrgId: '',
      roleId: '',
      tableData: [],
      adminName: '',
      editVisible: false,
      addOrEdit: 1,
      adminId: '',
      modelList: {
        account: { value: '', request: true, name: '账号', placeholder: '请输入账号', type: 'input' }, 
        password: { value: '', request: false, name: '密码', placeholder: '请输入密码', type: 'input' },
        realname: { value: '', request: true, name: '真实姓名', placeholder: '请输入真实姓名', type: 'input' },
        mobile: { value: '', request: true, name: '手机号', placeholder: '请输入手机号', type: 'input' },
        email: { value: '', request: true, name: '邮箱', placeholder: '请输入邮箱', type: 'input' },
        org_id: { value: '', request: true, name: '组', placeholder: '请选择组', type: 'select' },
        role_ids: { value: '', request: true, name: '角色', placeholder: '请选择角色', type: 'select' },
      },
      organizationData: [],
      currentPage: 1, //初始页
      pagesize: 10, //每页的数据
      total: null,
      idList: [] //选择的id数组
    };
  },
  mounted () {
    this.initAjaxMethod();
    this.orgAjaxMethod();
    this.roleAjaxMethod();
  },
  methods: {
    handleLog(id){
      this.$router.push({path:'/journalAdmin',query:{id}})
    },
    reset(){
      this.searchName='';
      this.currentPage=1;
      this.roleId='';
      this.initAjaxMethod();
    },
    mouseenter (data) {
      this.orgData.mouseenterId = data.id;
    },
    mouseleave () {
      this.orgData.mouseenterId = 0;
    },
    //新增一级
    firstBtn () {
      this.orgData.organizationId = 0;
      this.orgData.organizationName = '';
      this.orgData.editOrAdd = 1;
      this.orgData.editVisible = true;
      this.orangeTitle='新增组'
    },
    //列表新增组织
    append (data) {
      this.orgData.organizationName = '';
      this.orgData.editOrAdd = 1;
      this.orgData.organizationId = data.id;
      this.orgData.editVisible = true;
      this.orangeTitle='新增组'
    },
    //组织编辑
    orgEdit (data) {
      this.orgData.organizationId = data.parent_id;
      this.orgData.orgSelfId = data.id;
      this.orgData.editOrAdd = 2;
      this.orgData.organizationName = data.org_name;
      this.orgData.editVisible = true;
      this.orangeTitle='编辑组'
    },
    //列表删除组织
    orgRemove (data) {
      console.log(data);
      this.$confirm('此操作将永久删除该组, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.orgrRemoveMethod(data.id);
        })
        .catch(() => { });
    },
    //删除api
    orgrRemoveMethod (id) {
      const loading = this.$loading({ text: '删除中...' });
      this.$http
        .post(this.$API.ORGANIZATION_DEL, { id: id })
        .then(res => {
          loading.close();
          console.log('新增组', res);
          if (res.code == 1) {
            this.$message.success('删除成功');
            this.orgAjaxMethod();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    orgSaveEdit () {
      if (!this.orgData.organizationName) {
        this.$message.error('请填写组名称');
        return false;
      }
      this.orgData.editVisible = false;
      if (this.orgData.editOrAdd == 1) {
        this.addOrganization();
      } else {
        this.editOrganization();
      }
    },
    addOrganization () {
      const loading = this.$loading({ text: '保存中...' });
      this.$http
        .post(this.$API.ORGANIZATION_ADD, { org_name: this.orgData.organizationName, parent_id: this.orgData.organizationId })
        .then(res => {
          loading.close();
          console.log('新增组', res);
          if (res.code == 1) {
            this.$message.success('保存成功');
            this.orgAjaxMethod();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    }, //组织编辑api
    editOrganization () {
      const loading = this.$loading({ text: '保存中...' });
      this.$http
        .post(this.$API.ORGANIZATION_EDIT, {
          org_name: this.orgData.organizationName,
          parent_id: this.orgData.organizationId,
          id: this.orgData.orgSelfId
        })
        .then(res => {
          loading.close();
          console.log('新增组', res);
          if (res.code == 1) {
            this.$message.success('保存成功');
            this.orgAjaxMethod();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    adminSearch (data) {
      console.log(data.id);
      this.searchOrgId = data.id;
      this.handleSearch();
    },
    // 多选操作
    handleSelectionChange (val) {
      var emptyIdList = [];
      for (var i = 0; i < val.length; i++) {
        emptyIdList.push(val[i].id);
      }
      this.idList = emptyIdList;
      console.log(this.idList);
    },

    /**下面是管理员列表method */
    createBus () {
      for (let i in this.modelList) {
        this.modelList[i].value = '';
      }
      this.addOrEdit = 1;
      this.editVisible = true;
      this.roleListVal = [];
      this.organizationName = '';
      this.modelList.org_id.value = '';
      this.adminTitle='新建用户'
    },
    getCheckedNodes () {
      let nodes = this.$refs.org.getCheckedNodes();
      this.searchOrgId = nodes.length > 0 ? nodes[0].value : '';
    },
    //删除
    handleDelete (data) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.delAjaxMethod(data.id);
        })
        .catch(() => { });
    },
    //批量删除
    delAllSelection () {
      if (this.idList.length > 0) {
        this.$confirm('此操作将永久删除选中的用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.$http.post(this.$API.PERMISSION_BATCH_DEL, { ids: this.idList.join() }).then(res => {
              if (res.code == 1) {
                this.initAjaxMethod();
                this.$message({
                  type: 'success',
                  message: '批量删除成功!'
                });
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                });
              }
            });
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
      } else {
        this.$message({
          message: '请勾选需要删除的用户',
          type: 'warning'
        });
      }
    },
    //编辑
    handleEdit (data) {
      console.log(data);
      this.adminTitle='编辑用户';
      this.modelList.account.value = data.account;
      this.modelList.password.value = '******';
      this.modelList.realname.value = data.realname;
      this.modelList.mobile.value = data.mobile;
      this.modelList.email.value = data.email;
      this.modelList.org_id.value = data.org_id;
      this.roleListVal = data.role.map(item => item.id);
      this.modelList.role_ids.value = this.roleListVal.join(',');
      this.organizationName = data.org_name;
      this.adminId = data.id;
      this.addOrEdit = 2;
      this.editVisible = true;
    },
    jsMethod () {
      this.modelList.role_ids.value = this.roleListVal.join(',');
    },
    //搜索
    handleSearch () {
      this.initAjaxMethod();
    },
    //组织选择
    okClick (data) {
      this.modelList.org_id.value = data.id;
      this.organizationName = data.org_name;
    },
    //弹出框确定
    saveEdit () {
      if (this.addOrEdit == 1) {
        this.addAjaxMethod();
      } else {
        this.editAjaxMethod();
      }
    },
    //列表加载
    initAjaxMethod () {
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .post(this.$API.PERMISSION_INDEX, { org_id: this.searchOrgId, keyword: this.searchName, page: this.currentPage,roleId:this.roleId })
        .then(res => {
          loading.close();
          console.log('管理员列表', res);
          if (res.code == 1) {
            this.tableData = res.data.data;
            this.total = res.data.total;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //点击第几页
    handleCurrentChange (currentPage) {
      this.currentPage = currentPage;
      this.initAjaxMethod();
    },
    handleSizeChange(val){
      this.pageSize = val;
      this.initAjaxMethod();
    },
    //新增api
    addAjaxMethod () {
      //验证
      let test = this.testMethod();
      if (!test.flag) {
        this.$message.error(test.msg);
        return false;
      }
      const password=this.modelList.password.value;
      if(password && password.length<6){
        return this.$message.error('密码长度小于不能6位');
      }
      let data = {
        account: this.modelList.account.value,
        password: password,
        realname: this.modelList.realname.value,
        mobile: this.modelList.mobile.value,
        email: this.modelList.email.value,
        org_id: this.modelList.org_id.value,
        role_ids: this.modelList.role_ids.value,
      };
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .post(this.$API.PERMISSION_ADD, data)
        .then(res => {
          loading.close();
          console.log('管理员列表', res);
          if (res.code == 1) {
            this.$message.success('保存成功');
            this.editVisible = false;
            this.initAjaxMethod();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //删除api
    delAjaxMethod (id) {
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .post(this.$API.PERMISSION_DEL, { id: id })
        .then(res => {
          loading.close();
          console.log('管理员列表', res);
          if (res.code == 1) {
            this.$message.success('删除成功');
            this.initAjaxMethod();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //编辑api
    editAjaxMethod () {
      //验证
      let test = this.testMethod();
      if (!test.flag) {
        this.$message.error(test.msg);
        return false;
      }
      const password=this.modelList.password.value == '******'?'':this.modelList.password.value;
      if(password && password.length<6){
        return this.$message.error('密码长度不能小于6位');
      }
      let data = {
        account: this.modelList.account.value,
        password: password,
        realname: this.modelList.realname.value,
        mobile: this.modelList.mobile.value,
        email: this.modelList.email.value,
        org_id: this.modelList.org_id.value,
        role_ids: this.modelList.role_ids.value,
        id: this.adminId,
      };
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .post(this.$API.PERMISSION_EDIT, data)
        .then(res => {
          loading.close();
          console.log('管理员列表', res);
          if (res.code == 1) {
            this.$message.success('编辑成功');
            this.editVisible = false;
            this.initAjaxMethod();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //组织架构
    orgAjaxMethod () {
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .post(this.$API.ORGANIZATION_INDEX, {})
        .then(res => {
          loading.close();
          console.log('组织列表', res);
          if (res.code == 1) {
            this.organizationData = res.data;
            this.orgData.showOrgTree = false;
            this.$nextTick(() => {
              this.orgData.showOrgTree = true;
            });
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //角色列表
    roleAjaxMethod () {
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .post(this.$API.ROLE_INDEX, {})
        .then(res => {
          loading.close();
          console.log('角色列表', res);
          if (res.code == 1) {
            res.data.roleList.forEach(item => {
              item.active = false;
            });
            let roleList = res.data.roleList.filter(item => item.status == 1);
            this.roleList = roleList;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //验证方法
    testMethod () {
      let flag = true,
        msg = '';
      for (let i in this.modelList) {
        if (this.modelList[i].request) {
          if (i == 'mobile') {
            if (!/^1[3456789]\d{9}$/.test(this.modelList[i].value)) {
              flag = false;
              msg = '电话号码格式不正确';
              break;
            }
          } else if (i == 'email') {
            let reg = /^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/;
            if (!reg.test(this.modelList[i].value)) {
              flag = false;
              msg = '邮箱号码格式不正确';
              break;
            }
          } else {
            if (!this.modelList[i].value || this.modelList[i].value == '') {
              flag = false;
              msg = this.modelList[i].placeholder;
              break;
            }
          }
        }
      }
      return { flag: flag, msg: msg };
    }
  }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}
.handle-input {
    width: auto;
    display: inline-block;
}
.list-group {
    padding: 10px 0;
}
.list-title{
  /* padding:7px; */
  height: 32px; 
  display: flex;
  align-items: center;
}
.el-tree {
  min-width: 100%;
  display:inline-block !important;
}
</style>